package com.wq.order.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.collect.Sets;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.dubbo.remoting.TimeoutException;
import org.mengyun.tcctransaction.TransactionRepository;
import org.mengyun.tcctransaction.spring.recover.DefaultRecoverConfig;
import org.mengyun.tcctransaction.spring.repository.SpringJdbcTransactionRepository;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;

@Configuration
public class TccConfig {

    @Bean(name = "transactionRepository")
    public TransactionRepository getTransactionRepository() {
        SpringJdbcTransactionRepository transactionRepository = new SpringJdbcTransactionRepository();
        //transactionRepository.setDataSource(druidDataSource());
        transactionRepository.setDomain("red");
        transactionRepository.setTbSuffix("_red");

        //tcc所需分布式事务日志数据源（也可以使用其他数据源框架）
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        hikariDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/tcc?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=UTC");
        hikariDataSource.setUsername("root");
        hikariDataSource.setPassword("123456");
        transactionRepository.setDataSource(hikariDataSource);

        return transactionRepository;
    }

    /*@Bean("tccDataSource")
    // 将所有前缀为spring.datasource下的配置项都加载DataSource中
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }*/

    @Bean
    public DefaultRecoverConfig getDefaultRecoverConfig() {
        DefaultRecoverConfig recoverConfig = new DefaultRecoverConfig();
        recoverConfig.setDelayCancelExceptions(Sets.newHashSet(TimeoutException.class));
        return recoverConfig;
    }
}
